import React, { PureComponent, Fragment } from 'react';
import { connect } from 'dva';
import moment from 'moment';
import BraftEditor from 'braft-editor';
import 'braft-editor/dist/index.css';
import Upload from 'rc-upload';

import {
  Row,
  Col,
  Card,
  Form,
  Input,
  Select,
  Icon,
  Button,
  Dropdown,
  Menu,
  InputNumber,
  DatePicker,
  Modal,
  message,
  Checkbox,
  Radio,
  Badge,
  Divider,
} from 'antd';
const { RangePicker } = DatePicker;
const { TextArea } = Input;
const confirm = Modal.confirm;
import DescriptionList from 'components/DescriptionList';
const { Description } = DescriptionList;
const RadioGroup = Radio.Group;

import { articleAdd, articleUpdate } from '../../services/api';
import { getArrFromObj, getToken, getCurrent } from '../../utils/utils';
import config from '../../common/config';

import StandardTable from 'components/StandardTable';
import PageHeaderLayout from '../../layouts/PageHeaderLayout';

import styles from './article.less';

import uploadPng from '../../assets/upload.png';

const FormItem = Form.Item;
const { Option } = Select;
const getValue = obj =>
  Object.keys(obj)
    .map(key => obj[key])
    .join(',');

const PAGE_STATUS_MAP = {
  '0': '无效',
  '1': '有效',
};

const PAGE_STATUS_ARR = getArrFromObj(PAGE_STATUS_MAP);

const PAGE_CATEGORY_MAP = {
  1: '新闻动态',
  2: '政策资讯',
  3: '知产干货',
  4: '关于我们',
};

const PAGE_CATEGORY_ARR = getArrFromObj(PAGE_CATEGORY_MAP);

const PAGE_SIZE = 10;

@connect(({ article, loading }) => {
  return {
    article,
    loading: loading.models.article,
  };
})
@Form.create()
export default class List extends PureComponent {
  state = {
    modalVisible: false,
    selectedRows: [],
    formValues: {},
    id: null,

    title: null,
    status: '1',
    category: '1',
    author: getCurrent().username,

    pcTitle: null,
    pcKeywords: null,
    pcDesc: null,
    mobileTitle: null,
    mobileKeywords: null,
    mobileDesc: null,
    content: '',

    imgOptions: {},
    coverUrl: null,
  };

  componentDidMount() {
    this.getImgOptions();
    this.init();
  }

  getImgOptions() {
    const token = getToken();

    const imgOptions = {
      action: config.serveraddress + '/upload/putObject?dataType=0',
      data: { dataType: 0 },
      headers: {
        Authorization: 'Bearer ' + token,
      },
      multiple: false,
      beforeUpload(file) {
        console.log('beforeUpload', file.name);
      },
      onStart: file => {
        console.log('onStart', file.name);
      },
      onProgress(step, file) {},
    };

    this.setState({
      imgOptions,
    });
  }

  init() {
    const { dispatch } = this.props;
    dispatch({
      type: 'article/queryList',
      payload: {
        pageNum: 1,
        pageSize: PAGE_SIZE,
      },
    });
  }

  handleStandardTableChange = (pagination, filtersArg, sorter) => {
    const { dispatch } = this.props;
    const { formValues } = this.state;

    const filters = Object.keys(filtersArg).reduce((obj, key) => {
      const newObj = { ...obj };
      newObj[key] = getValue(filtersArg[key]);
      return newObj;
    }, {});

    const params = {
      ...formValues,
      ...filters,
      pageNum: pagination.current,
      pageSize: pagination.pageSize,
    };
    if (sorter.field) {
      params.sorter = `${sorter.field}_${sorter.order}`;
    }

    dispatch({
      type: 'article/queryList',
      payload: params,
    });
  };

  handleFormReset = () => {
    const { form, dispatch } = this.props;
    form.resetFields();
    this.setState({
      formValues: {},
    });
    dispatch({
      type: 'article/queryList',
      payload: {
        pageNum: 1,
        pageSize: PAGE_SIZE,
      },
    });
  };

  handleSelectRows = rows => {
    this.setState({
      selectedRows: rows,
    });
  };

  handleSearch = e => {
    e.preventDefault();

    const { dispatch, form } = this.props;

    form.validateFields((err, fieldsValue) => {
      if (err) return;

      if (fieldsValue.createTime) {
        fieldsValue.startTime =
          moment(fieldsValue.createTime[0]).format('YYYY-MM-DD') + 'T00:00:00Z';
        fieldsValue.endTime = moment(fieldsValue.createTime[1]).format('YYYY-MM-DD') + 'T23:59:59Z';
      }

      delete fieldsValue['createTime'];

      const values = {
        ...fieldsValue,
        pageNum: 1,
        pageSize: PAGE_SIZE,
      };

      dispatch({
        type: 'article/queryList',
        payload: values,
      });
    });
  };

  handleShowModal = e => {
    e.preventDefault();
    this.setState({
      id: null,
      modalVisible: true,
      levelRule: '',
      name: '',
    });
  };

  handleCancel = e => {
    this.setState({
      modalVisible: false,
    });
  };

  async handleSave(e) {
    const {
      title,
      status,
      category,
      author,
      coverUrl,
      pcTitle,
      pcKeywords,
      pcDesc,
      mobileTitle,
      mobileKeywords,
      mobileDesc,
      content,
    } = this.state;
    if (!title) {
      return message.error('请填写文章标题');
    }

    if (!author) {
      return message.error('请填写文章作者');
    }

    if (!category) {
      return message.error('请选择文章分类');
    }

    if (!content) {
      return message.error('请填写文章内容');
    }

    await this.doSave();
  }

  async doSave() {
    const { dispatch } = this.props;

    const {
      id,
      title,
      status,
      category,
      author,
      coverUrl,
      pcTitle,
      pcKeywords,
      pcDesc,
      mobileTitle,
      mobileKeywords,
      mobileDesc,
      content,
    } = this.state;

    let response = {};
    if (id) {
      const params = {
        id,
        title,
        status,
        category,
        author,
        coverUrl,
        pcTitle,
        pcKeywords,
        pcDesc,
        mobileTitle,
        mobileKeywords,
        mobileDesc,
        content: content.toHTML(),
      };
      response = await articleUpdate(params);
    } else {
      const params = {
        title,
        status,
        category,
        author,
        coverUrl,
        pcTitle,
        pcKeywords,
        pcDesc,
        mobileTitle,
        mobileKeywords,
        mobileDesc,
        content: content.toHTML(),
      };
      response = await articleAdd(params);
    }

    if (response.code === 200) {
      this.setState({
        modalVisible: false,
      });

      this.init();
    } else {
      message.error(response.message);
    }
  }

  handleReply(item) {
    this.setState({
      ...item,
      modalVisible: true,
    });
  }

  handleOnchange(field, e) {
    this.setState({
      [field]: e.target.value,
    });
  }

  onChange(field, value, dateString) {
    this.setState({
      [field]: dateString,
    });
  }

  handleSelectOnchange(field, value) {
    this.setState({
      [field]: value,
    });
  }

  onRadioChange(field, e) {
    this.setState({
      [field]: e.target.value,
    });
  }

  handleEdit(item) {
    this.setState({
      ...item,
      content: BraftEditor.createEditorState(item.content),
      modalVisible: true,
    });
  }

  renderForm() {
    return this.renderAdvancedForm();
  }

  renderAdvancedForm() {
    const { getFieldDecorator } = this.props.form;
    return (
      <Form onSubmit={this.handleSearch} layout="inline">
        <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
          <Col md={8} sm={24}>
            <span style={{ float: 'left', marginBottom: 24 }}>
              <Button type="primary" onClick={this.handleShowModal.bind(this)}>
                新增文章
              </Button>
            </span>
          </Col>
          <Col md={8} sm={24} />
          <Col md={8} sm={24} />
        </Row>
      </Form>
    );
  }

  handleEditorChange = editorState => {
    this.setState({
      content: editorState,
    });
  };

  uploadSuccess(res, field) {
    this.setState({
      [field]: res.data,
    });
  }

  uploadError(res, field) {
    debugger;
  }

  render() {
    let { article: { data }, loading } = this.props;
    const { getFieldDecorator } = this.props.form;
    const { selectedRows, modalVisible, imgOptions, coverUrl } = this.state;

    const columns = [
      {
        title: '序号',
        dataIndex: 'id',
        render: (val, item, index) => (
          <span>{(data.pagination.current - 1) * data.pagination.pageSize + index + 1}</span>
        ),
      },
      {
        title: '标题',
        ellipsis: true,
        width: 100,
        dataIndex: 'title',
      },
      {
        title: '浏览量',
        dataIndex: 'a',
      },
      {
        title: '文章状态',
        dataIndex: 'status',
        render: val => <span>{PAGE_STATUS_MAP[val] || '-'}</span>,
      },
      {
        title: '添加人',
        dataIndex: 'createUser',
        render: val => <span>{val || '-'}</span>,
      },
      {
        title: '发布日期',
        dataIndex: 'createTime',
        render: val => <span>{val ? moment(val).format('YYYY-MM-DD') : '-'}</span>,
      },
      {
        title: '操作',
        dataIndex: '',
        render: (val, item) => (
          <span>
            <a href="javascript:;" onClick={this.handleEdit.bind(this, item)}>
              编辑
            </a>
          </span>
        ),
      },
    ];

    return (
      <PageHeaderLayout title="文章管理">
        <Card bordered={false}>
          <div className={styles.tableList}>
            <div className={styles.tableListForm}>{this.renderForm()}</div>
            <StandardTable
              disableSelect={true}
              selectedRows={selectedRows}
              loading={loading}
              data={data}
              columns={columns}
              onSelectRow={this.handleSelectRows}
              onChange={this.handleStandardTableChange}
            />
          </div>
        </Card>

        <Modal
          maskClosable={false}
          width="70%"
          title="新增文章"
          visible={this.state.modalVisible}
          onOk={this.handleSave.bind(this)}
          onCancel={this.handleCancel.bind(this)}
        >
          <Row gutter={{ md: 24, lg: 24, xl: 24 }}>
            <Col span={12}>
              <DescriptionList size="large" title="" style={{ width: '100%', margin: '10px' }}>
                <Description term="文章标题">
                  <Input
                    style={{ width: '300px' }}
                    value={this.state.title}
                    onChange={this.handleOnchange.bind(this, 'title')}
                  />
                </Description>
              </DescriptionList>
            </Col>
            <Col span={12}>
              <DescriptionList size="large" title="" style={{ width: '100%', margin: '10px' }}>
                <Description term="文章作者">
                  <Input
                    style={{ width: '200px' }}
                    value={this.state.author}
                    onChange={this.handleOnchange.bind(this, 'author')}
                  />
                </Description>
              </DescriptionList>
            </Col>
          </Row>
          <Row gutter={{ md: 8, lg: 24, xl: 24 }}>
            <Col md={12} sm={24}>
              <DescriptionList size="large" title="" style={{ width: '100%', margin: '10px' }}>
                <Description term="文章状态">
                  <Select
                    style={{ width: '200px' }}
                    placeholder=""
                    value={this.state.status + ''}
                    onChange={this.handleSelectOnchange.bind(this, 'status')}
                  >
                    {PAGE_STATUS_ARR.map(item => {
                      return (
                        <Option key={item.id} value={item.id}>
                          {item.name}
                        </Option>
                      );
                    })}
                  </Select>
                </Description>
              </DescriptionList>
            </Col>
            <Col md={12} sm={24}>
              <DescriptionList size="large" title="" style={{ width: '100%', margin: '10px' }}>
                <Description term="文章分类">
                  <Select
                    style={{ width: '200px' }}
                    placeholder=""
                    value={this.state.category + ''}
                    onChange={this.handleSelectOnchange.bind(this, 'category')}
                  >
                    {PAGE_CATEGORY_ARR.map(item => {
                      return (
                        <Option key={item.id} value={item.id}>
                          {item.name}
                        </Option>
                      );
                    })}
                  </Select>
                </Description>
              </DescriptionList>
            </Col>
          </Row>

          <Divider orientation="left">SEO 设置</Divider>

          <Row gutter={{ md: 24, lg: 24, xl: 24 }}>
            <Col span={12}>
              <DescriptionList size="large" title="" style={{ width: '100%', margin: '10px' }}>
                <Description term="PC Title">
                  <Input
                    style={{ width: '200px' }}
                    value={this.state.pcTitle}
                    onChange={this.handleOnchange.bind(this, 'pcTitle')}
                  />
                </Description>
              </DescriptionList>
            </Col>
            <Col span={12}>
              <DescriptionList size="large" title="" style={{ width: '100%', margin: '10px' }}>
                <Description term="移动端 Title">
                  <Input
                    style={{ width: '200px' }}
                    value={this.state.mobileTitle}
                    onChange={this.handleOnchange.bind(this, 'mobileTitle')}
                  />
                </Description>
              </DescriptionList>
            </Col>
          </Row>

          <Row gutter={{ md: 24, lg: 24, xl: 24 }}>
            <Col span={12}>
              <DescriptionList size="large" title="" style={{ width: '100%', margin: '10px' }}>
                <Description term="PC Keywords">
                  <Input
                    style={{ width: '200px' }}
                    value={this.state.pcKeywords}
                    onChange={this.handleOnchange.bind(this, 'pcKeywords')}
                  />
                </Description>
              </DescriptionList>
            </Col>
            <Col span={12}>
              <DescriptionList size="large" title="" style={{ width: '100%', margin: '10px' }}>
                <Description term="移动端 Keywords">
                  <Input
                    style={{ width: '200px' }}
                    value={this.state.mobileKeywords}
                    onChange={this.handleOnchange.bind(this, 'mobileKeywords')}
                  />
                </Description>
              </DescriptionList>
            </Col>
          </Row>

          <Row gutter={{ md: 24, lg: 24, xl: 24 }}>
            <Col span={12}>
              <DescriptionList size="large" title="" style={{ width: '100%', margin: '10px' }}>
                <Description term="PC Description">
                  <Input
                    style={{ width: '200px' }}
                    value={this.state.pcDesc}
                    onChange={this.handleOnchange.bind(this, 'pcDesc')}
                  />
                </Description>
              </DescriptionList>
            </Col>
            <Col span={12}>
              <DescriptionList size="large" title="" style={{ width: '100%', margin: '10px' }}>
                <Description term="移动端 Description">
                  <Input
                    style={{ width: '200px' }}
                    value={this.state.mobileDesc}
                    onChange={this.handleOnchange.bind(this, 'mobileDesc')}
                  />
                </Description>
              </DescriptionList>
            </Col>
          </Row>

          <Divider orientation="left">文章封面</Divider>

          <Upload
            {...imgOptions}
            onSuccess={res => {
              this.uploadSuccess(res, 'coverUrl');
            }}
            onError={res => {
              this.uploadError(res, 'coverUrl');
            }}
            ref="inner"
          >
            <div id="demo1" style={{ width: '200px', textAlign: 'center' }}>
              <img style={{ width: '200px' }} src={coverUrl || uploadPng} />
              <div>点击上传</div>
            </div>
          </Upload>

          <Divider orientation="left">页面详情</Divider>

          <Row gutter={{ md: 24, lg: 24, xl: 24 }}>
            <Col span={24}>
              <DescriptionList style={{ width: '100%' }} size="large" title="" col="1">
                <div style={{ border: '1px solid #ccc' }}>
                  <BraftEditor
                    value={this.state.content}
                    onChange={this.handleEditorChange.bind(this)}
                  />
                </div>
              </DescriptionList>
            </Col>
          </Row>
        </Modal>
      </PageHeaderLayout>
    );
  }
}
